package com.jaya.budan.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.jaya.budan.R;
import com.jaya.budan.activity.Chat_Activity;
import com.jaya.budan.adapter.Chat_ListView_Adapter;
import com.jaya.budan.base.BaseFragment;
import com.jaya.budan.bean.User_Limit;
import com.jaya.budan.thirdpush.Menu;
import com.jaya.budan.utils.ToolUtils;
import com.jaya.budan.views.MyListView;
import com.tencent.imsdk.v2.V2TIMConversation;
import com.tencent.imsdk.v2.V2TIMConversationListener;
import com.tencent.imsdk.v2.V2TIMConversationResult;
import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.imsdk.v2.V2TIMUserFullInfo;
import com.tencent.imsdk.v2.V2TIMValueCallback;
import com.tencent.qcloud.tim.uikit.component.action.PopActionClickListener;
import com.tencent.qcloud.tim.uikit.component.action.PopMenuAction;
import com.tencent.qcloud.tim.uikit.modules.chat.base.ChatInfo;
import com.tencent.qcloud.tim.uikit.modules.conversation.ConversationLayout;
import com.tencent.qcloud.tim.uikit.modules.conversation.ConversationListLayout;
import com.tencent.qcloud.tim.uikit.modules.conversation.base.ConversationInfo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ChatFragment extends BaseFragment implements View.OnClickListener{

    private EditText et_chat_sousuo;
    private MyListView main_listview;
    private String access_token, uid;
    private ArrayList<User_Limit> user_limitList;
    private List<V2TIMConversation> uiConvList = new ArrayList();
    private ConversationLayout conversation_layout;
    private Menu mMenu;
    private View view;
    private SharedPreferences preferences;
    public Chat_ListView_Adapter adapter;
    private List<PopMenuAction> mConversationPopActions = new ArrayList<>();
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_chat, container, false);
        et_chat_sousuo = view.findViewById(R.id.et_chat_sousuo);
        main_listview = view.findViewById(R.id.main_listview);
        // 从布局文件中获取会话列表面板
        conversation_layout = view.findViewById(R.id.conversation_layout);
        Bundle bundle = getArguments();
        access_token = bundle.getString("access_token");
        uid = bundle.getString("uid");
        preferences = getActivity().getSharedPreferences("user_message", Context.MODE_PRIVATE);
        mMenu = new Menu(getActivity(), conversation_layout.getTitleBar(), Menu.MENU_TYPE_CONVERSATION, user_limitList);
        getHHlist();
        fangfa();
        main_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //此处为demo的实现逻辑，更根据会话类型跳转到相关界面，开发者可根据自己的应用场景灵活实现
                ChatInfo chatInfo = new ChatInfo();
//                chatInfo.setType(conversationInfo.isGroup() ? V2TIMConversation.V2TIM_GROUP : V2TIMConversation.V2TIM_C2C);
                chatInfo.setType(V2TIMConversation.V2TIM_C2C);
                chatInfo.setId(uiConvList.get(position).getUserID() + "");
                chatInfo.setChatName(user_limitList.get(position).getNicename() + "");
                Intent intent = new Intent(getActivity(), Chat_Activity.class);
                intent.putExtra("access_token", access_token);
                intent.putExtra("roomId", uiConvList.get(position).getUserID() + "");
                intent.putExtra("chatInfo", chatInfo);
                intent.putExtra("user_limit", user_limitList.get(position));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
//        main_listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
//            @Override
//            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//                ChatInfo chatInfo = new ChatInfo();
////                chatInfo.setType(conversationInfo.isGroup() ? V2TIMConversation.V2TIM_GROUP : V2TIMConversation.V2TIM_C2C);
//                chatInfo.setType(V2TIMConversation.V2TIM_C2C);
//                chatInfo.setId(uiConvList.get(position).getUserID() + "");
//                chatInfo.setChatName(TUIKitConfigs.getConfigs().getGeneralConfig().getUserNickname());
//                //长按会话item弹框
//                if (mConversationPopActions == null || mConversationPopActions.size() == 0){
//                    return true;
//                }
//                View itemPop = LayoutInflater.from(getActivity()).inflate(R.layout.pop_menu_layout, null);
//                ListView mConversationPopList = itemPop.findViewById(R.id.pop_menu_list);
//                mConversationPopList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//                    @Override
//                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                        PopMenuAction action = mConversationPopActions.get(position);
//                        if (action.getActionClickListener() != null) {
//                            action.getActionClickListener().onActionClick(position, chatInfo);
//                        }
//                    }
//                });
//                for (int i = 0; i < mConversationPopActions.size(); i++) {
//                    PopMenuAction action = mConversationPopActions.get(i);
//                    if (true) {
//                        if (action.getActionName().equals("置顶聊天")) {
//                            action.setActionName("取消置顶");
//                        }
//                    } else {
//                        if (action.getActionName().equals("取消置顶")) {
//                            action.setActionName("置顶聊天");
//                        }
//                    }
//                }
//                PopDialogAdapter mConversationPopAdapter = new PopDialogAdapter();
//                mConversationPopList.setAdapter(mConversationPopAdapter);
////                mConversationPopList.setAdapter(new NearBy_ListView_Adapter(getActivity(), user_limitList, 1));
//                mConversationPopAdapter.setDataSource(mConversationPopActions);
//                PopupWindow mConversationPopWindow = PopWindowUtil.popupWindow(itemPop, view, (int) view.getX(), (int) view.getY() + view.getHeight() / 2);
//                view.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        mConversationPopWindow.dismiss();
//                    }
//                }, 10000); // 10s后无操作自动消失
//                return true;
//            }
//        });
        et_chat_sousuo.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        return view;
    }

    public static ChatFragment newInstance() {
        Bundle args = new Bundle();
        ChatFragment fragment = new ChatFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_main_near_by_jilu:
                break;
            default:
                break;
        }
    }

    private void fangfa() {
        // 会话列表面板的默认UI和交互初始化
        conversation_layout.initDefault();
        // 通过API设置ConversataonLayout各种属性的样例，开发者可以打开注释，体验效果
//        ConversationLayoutHelper.customizeConversation(conversation_layout);
        conversation_layout.getConversationList().setItemTopTextSize(16); // 设置adapter item中top文字大小
        conversation_layout.getConversationList().setItemBottomTextSize(12);// 设置adapter item中bottom文字大小
        conversation_layout.getConversationList().setItemDateTextSize(10);// 设置adapter item中timeline文字大小
        conversation_layout.getConversationList().setItemAvatarRadius(5);// 设置adapter item头像圆角大小
        conversation_layout.getConversationList().disableItemUnreadDot(true);// 设置adapter item是否不显示未读红点，默认显示
        // 动态插入，删除Item，包括自定义会话
        final ConversationInfo customInfo = new ConversationInfo();
        customInfo.setType(ConversationInfo.TYPE_CUSTOM);
        customInfo.setId("自定义会话");
        customInfo.setGroup(false);
        customInfo.setTitle("乔丹风行8代跑鞋 风随我动！");
//        conversation_layout.getConversationList().setAdapter(new NearBy_ListView_Adapter(getActivity(), user_limitList, 1));
        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
//                conversation_layout.addConversationInfo(0, customInfo);
            }
        }, 3000);
        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
//                conversation_layout.removeConversationInfo(0);
            }
        }, 5000);
        conversation_layout.getConversationList().setOnItemClickListener(new ConversationListLayout.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position, ConversationInfo conversationInfo) {
                //此处为demo的实现逻辑，更根据会话类型跳转到相关界面，开发者可根据自己的应用场景灵活实现
                ChatInfo chatInfo = new ChatInfo();
//                chatInfo.setType(conversationInfo.isGroup() ? V2TIMConversation.V2TIM_GROUP : V2TIMConversation.V2TIM_C2C);
                chatInfo.setType(V2TIMConversation.V2TIM_C2C);
                chatInfo.setId(conversationInfo.getId());
                chatInfo.setChatName(conversationInfo.getTitle());
                Intent intent = new Intent(getActivity(), Chat_Activity.class);
                intent.putExtra("access_token", access_token);
                intent.putExtra("roomId", uiConvList.get(position).getUserID() + "");
                intent.putExtra("chatInfo", chatInfo);
                intent.putExtra("user_limit", user_limitList.get(position));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
        conversation_layout.getConversationList().setOnItemLongClickListener(new ConversationListLayout.OnItemLongClickListener() {
            @Override
            public void OnItemLongClick(View view, int position, ConversationInfo conversationInfo) {

            }
        });
//        conversation_layout.getTitleBar().setOnRightClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                if (mMenu.isShowing()) {
//                    mMenu.hide();
//                } else {
//                    mMenu.show();
//                }
//            }
//        });
        conversation_layout.getTitleBar().setVisibility(View.GONE);
        // 设置长按conversation显示PopAction
        List<PopMenuAction> conversationPopActions = new ArrayList<>();
        PopMenuAction action = new PopMenuAction();
        action.setActionName("置顶聊天");
        action.setActionClickListener(new PopActionClickListener() {
            @Override
            public void onActionClick(int position, Object data) {
                conversation_layout.setConversationTop(position, customInfo);
            }
        });
        conversationPopActions.add(action);
        action = new PopMenuAction();
        action.setActionClickListener(new PopActionClickListener() {
            @Override
            public void onActionClick(int position, Object data) {
                conversation_layout.deleteConversation(position, customInfo);
            }
        });
        action.setActionName("删除聊天");
        conversationPopActions.add(action);
        mConversationPopActions.clear();
        mConversationPopActions.addAll(conversationPopActions);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        getHHlist();
    }

    private void getHHlist(){
        // 1. 设置会话监听
        V2TIMManager.getConversationManager().setConversationListener(new V2TIMConversationListener() {
            @Override
            public void onNewConversation(List<V2TIMConversation> conversationList) {
                super.onNewConversation(conversationList);
                updateConversation(conversationList, true);//收到会话新增的回调
            }

            @Override
            public void onConversationChanged(List<V2TIMConversation> conversationList) {
                super.onConversationChanged(conversationList);
                updateConversation(conversationList, true);//收到会话更新的回调
            }
        });
        // 2. 先拉取50个本地会话做 UI 展示，nextSeq 第一次拉取传0
        V2TIMManager.getConversationManager().getConversationList(0, 50,
                new V2TIMValueCallback<V2TIMConversationResult>() {
                    @Override
                    public void onError(int code, String desc) {
                        // 拉取会话列表失败
                    }

                    @Override
                    public void onSuccess(V2TIMConversationResult v2TIMConversationResult) {
                        // 拉取成功，更新 UI 会话列表
                        updateConversation(v2TIMConversationResult.getConversationList(), false);
                        if (!v2TIMConversationResult.isFinished()) {
                            V2TIMManager.getConversationManager().getConversationList(v2TIMConversationResult.getNextSeq(), 50,
                                    new V2TIMValueCallback<V2TIMConversationResult>() {
                                        @Override
                                        public void onError(int code, String desc) {
                                        }

                                        @Override
                                        public void onSuccess(V2TIMConversationResult v2TIMConversationResult) {
                                            // 拉取成功，更新 UI 会话列表
                                            updateConversation(v2TIMConversationResult.getConversationList(), false);
                                        }
                                    });
                        }
                    }
                });
    }

    private void updateConversation(List<V2TIMConversation> convList, boolean needSort) {
        for (int i = 0; i < convList.size(); i++) {
            V2TIMConversation conv = convList.get(i);
            boolean isExit = false;
            for (int j = 0; j < uiConvList.size(); j++) {
                V2TIMConversation uiConv = uiConvList.get(j);
                // UI 会话列表存在该会话，则替换
                if (uiConv.getConversationID().equals(conv.getConversationID())) {
                    uiConvList.set(j, conv);
                    isExit = true;
                    break;
                }
            }
            // UI 会话列表没有该会话，则新增
            if (!isExit) {
                uiConvList.add(conv);
            }
        }
        // 4. 按照会话 lastMessage 的 timestamp 对 UI 会话列表做排序并更新界面
        if (needSort) {
            Collections.sort(uiConvList, new Comparator<V2TIMConversation>() {
                @Override
                public int compare(V2TIMConversation o1, V2TIMConversation o2) {
                    if (o1.getLastMessage().getTimestamp() > o2.getLastMessage().getTimestamp()) {
                        return -1;
                    } else {
                        return 1;
                    }
                }
            });
        }
        Log.d("main_chat", JSON.toJSONString(uiConvList));
        user_limitList = new ArrayList<>();
        for(V2TIMConversation v2TIMConversation :uiConvList){
            Log.d("v2TIMConversation", JSON.toJSONString(v2TIMConversation));
            String tencentUserStr = preferences.getString(ToolUtils.getTencentUserDBKey(v2TIMConversation.getUserID()), "");
            String user = preferences.getString("user_limit_" + v2TIMConversation.getUserID(), "");
            Log.d("main_user", user);
            if(!ToolUtils.isEmpty(user)){
                User_Limit tencentUser = JSON.parseObject(user, User_Limit.class);
                tencentUser.setV2TIMConversation(v2TIMConversation);
                user_limitList.add(tencentUser);
                List<String> userIDList = new ArrayList<>();
                userIDList.add(v2TIMConversation.getUserID() + "");
                V2TIMManager.getInstance().getUsersInfo(userIDList, new V2TIMValueCallback<List<V2TIMUserFullInfo>>() {
                    @Override
                    public void onError(int i, String s) {

                    }
                    @Override
                    public void onSuccess(List<V2TIMUserFullInfo> v2TIMUserFullInfos) {
                        Log.d("main_chat_vfi", JSON.toJSONString(v2TIMUserFullInfos));
                    }
                });
            }
        }
        Log.d("main_chat_list", JSON.toJSONString(user_limitList));
        adapter = new Chat_ListView_Adapter(getActivity(), user_limitList);
        main_listview.setAdapter(adapter);
    }
}